import { ApiCall } from "tsrpc";
import { ReqRenameFile, ResRenameFile } from "../../shared/protocols/SourceManage/PtlRenameFile";
import { Global } from "../../Global";
import { findFolder } from "../../utils/FindCurrentFolder";

export default async function (call: ApiCall<ReqRenameFile, ResRenameFile>) {
    // TODO
    const course = call.req.course
    const root = await Global.collection('folders').findOne({
        course
    })
    if(!root) return call.error('课程不存在')

    const folder = findFolder(call.req.path,root)
    if(!folder) return call.error('文件夹不存在')

    const file = folder.files.find(f => f.name === call.req.name)
    if(!file) return call.error('文件不存在')

    file.name = call.req.newName

    await Global.collection('folders').updateOne({
        course
    },{
        $set:{
            folders:root.folders
        }
    })

    call.succ({
        files:folder.files,
        folders:folder.folders.map(f => f.name)
    })
}